<template>
  <div class="app-container questions-new">
    <el-card>
      <!-- 头部 -->
      <div slot="header">
        {{ $route.query.id?"试题修改":'试题录入' }}
      </div>

      <!-- form表单 -->
      <el-form ref="qsForm" :model="qsForm" :rules="qsRules" class="form" label-width="120px">
        <!-- 学科选择器 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="qsForm.subjectID" placeholder="请选择" style="width:400px" @change="changeSubject">
            <el-option v-for="item in subjectName " :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 目录选择器 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="qsForm.catalogID" placeholder="请选择" style="width:400px">
            <el-option v-for="item in directorys" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 企业选择器 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="qsForm.enterpriseID" placeholder="请选择" style="width:400px">
            <el-option v-for="item in company" :key="item.id" :label="item.company" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 城市选择器 -->
        <el-form-item label="城市：" prop="city">
          <el-select v-model="qsForm.province" placeholder="请选择" style="width:198px " @change="chagneCity">
            <el-option v-for="(item,index) in cityOptions " :key="index" :label="item" :value="item" />
          </el-select>
          <el-select v-model="qsForm.city" placeholder="请选择" style="width:198px; margin-left:4px">
            <el-option v-for="(item,index) in areaOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- 方向选择 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="qsForm.direction" placeholder="请选择" style="width:400px">
            <el-option v-for="(item,index) in directionOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- 题型  与选项联动-->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="qsForm.questionType" size="mini" @change="changeOption({})">
            <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="qsForm.difficulty" size="mini">
            <el-radio v-for="item in difficulty " :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干：" prop="question">
          <quill-editor
            v-model="qsForm.question"
            :options="editorOption"
            @blur="checkQuestion"
          />
        </el-form-item>
        <!-- 选项  -->
        <el-form-item v-if="qsForm.questionType!=='3'" label="选项：" prop="options">
          <div v-for="item in qsForm.options" :key="item.code" class="option_item">
            <el-radio v-if="qsForm.questionType==='1'" v-model="item.isRight" :label="true" style="margin-right:0" @change="changeOption(item)">{{ item.code+"：" }}</el-radio>
            <el-checkbox v-if="qsForm.questionType==='2'" v-model="item.isRight" :label="true">  {{ item.code+"：" }}</el-checkbox>
            <el-input v-model="item.title" style="width:200px" />
            <el-upload
              class="avatar-uploader"
              list-type="picture-card"
              action="https://jsonplaceholder.typicode.com/posts/"
              :headers="{'Authorization':'Bearer '+ token}"
              :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
              :show-file-list="false"
            >
              <img v-if="item.img" :src="item.img" class="avatar">
              <span v-else>上传图片</span>
              <i v-if="!item.img" class="el-icon-circle-close" />

            </el-upload>
          </div>
          <el-button type="danger" :disabled="qsForm.questionType!=='2' " @click="addOption">+增加选项与答案</el-button>

        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input v-model="qsForm.videoURL" style="width:400px" />

        </el-form-item>
        <!-- 答案解析 富文本-->
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor
            v-model="qsForm.answer"
            :options="editorOption"
            @blur="checkAnswer"
          />

        </el-form-item>
        <!-- 题目备注  -->
        <el-form-item label="题目备注：">
          <el-input v-model="qsForm.remarks" type="textarea" style="width:400px;" size="medium" :autosize="{ minRows: 5, maxRows: 10}" />

        </el-form-item>
        <!-- 试题标签  选择器-->
        <el-form-item label="试题标签: " prop="tags">
          <el-select
            v-model="qsForm.tags"
            placeholder="请选择试题标签"
            style="width:400px"
            allow-create
            filterable
            default-first-option
            multiple
          >
            <el-option v-for="item in tagName " :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <!-- 确认提交按钮 -->
        <el-form-item>
          <el-button v-if="$route.query.id" type="success" @click="clickUpdata($route.query.id)">确认修改</el-button>
          <el-button v-else type="primary" @click="clickSubmit">确认提交</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import { simple as getSubjectOptions } from '@/api/hmmm/subjects.js'
import { simple as getDirectoryOptions } from '@/api/hmmm/directorys'
import { simple as getTagsOptions } from '@/api/hmmm/tags.js'
import { list as getCompanyOptions } from '@/api/hmmm/companys.js'
import { provinces as getCityOptions, citys as getAreaOptions } from '@/api/hmmm/citys.js'
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
import { detail, add, update } from '@/api/hmmm/questions.js'
import { getToken } from '@/utils/auth'

// 富文本代码高亮
import hljs from 'highlight.js'

import 'highlight.js/styles/monokai-sublime.css'

// 导入富文本编辑器
import { quillEditor } from 'vue-quill-editor'
// 导入富文本编辑器样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data() {
    return {
      token: getToken(),
      subjectName: [], // 学科选项
      directorys: [], // 目录选项
      company: [], // 企业选项
      cityOptions: getCityOptions(), // 城市选项
      areaOptions: [], // 地区选项
      directionOptions: direction, // 方向选项
      questionType, // 题型
      difficulty, // 难度
      tagName: [], // 标签选项

      //  表单
      qsForm: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 题干
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]

      },
      // 表单验证
      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请选择试题标签', trigger: 'blur' }
        ]

      },

      // 富文本的配置
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用  代码块
            ['code-block', 'image', 'link'] // 链接、图片、视频
          ] // 工具菜单栏配置
        },
        syntax: {
          highlight: text => hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
        }
      }

    }
  },
  watch: {
    '$route.query': function() {
      if (this.$route.query.id) {
        this.getQuestions()
      } else {
        this.qsForm = {
          subjectID: null, // 学科
          catalogID: null, // 目录
          enterpriseID: null, // 企业
          province: null, // 城市
          city: null, // 地区
          direction: null, // 方向
          questionType: '1', // 题型
          difficulty: '1', // 难度
          question: null, // 题干
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.qsForm.resetFields()
        })
      }
    }

  },
  created() {
    this.getSubjectOptions()
    this.getCompanyOptions()
    if (this.$route.query.id) {
      this.getQuestions()
    }
  },
  methods: {

    // 获取列表详情
    async getQuestions() {
      const { data } = await detail({ id: this.$route.query.id })
      // console.log(res)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.qsForm = data
      const res1 = await getDirectoryOptions({ subjectID: this.qsForm.subjectID })
      this.directorys = res1.data
      const res2 = await getTagsOptions({ subjectID: this.qsForm.subjectID })
      this.tagName = res2.data

      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    // 检验题干
    checkQuestion() {
      this.$refs.qsForm.validateField('question')
    },
    checkAnswer() {
      this.$refs.qsForm.validateField('answer')
    },

    // 上传成功
    uploadSuccess(item, res, file) {
      console.log(item, file)
      item.img = URL.createObjectURL(file.raw)
    },

    // 添加选项
    addOption() {
      this.qsForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.qsForm.options.length),
        title: '',
        img: ''
      })
    },

    // 单选框 选择题型
    changeOption(val) {
      // console.log(e)
      // this.value = val
      this.qsForm.options.forEach(item => {
        item.isRight = false
      })
      val.isRight = true
    },
    // 城市与地区的层级
    chagneCity(cityName) {
      this.qsForm.city = null
      this.areaOptions = getAreaOptions(cityName)
    },

    // 确认修改
    clickUpdata() {
      this.$refs.qsForm.validate(async flag => {
        if (!flag) return this.$message.error('请完善内容')
        const data = { ...this.qsForm }
        data.tags = data.tags.join(',')
        await update(data)
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
      })
    },

    // 确认提交
    async clickSubmit() {
      this.$refs.qsForm.validate(async flag => {
        if (!flag) return this.$message.error('请完善内容')
        const data = { ...this.qsForm }
        data.tags = data.tags.join(',')
        await add(data)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      })
    },

    // 改变学科 学科联动（目录与标签）
    async changeSubject(subjectID) {
      // 目录 请求
      this.qsForm.catalogID = null
      const res1 = await getDirectoryOptions({ subjectID: this.qsForm.subjectID })
      this.directorys = res1.data
      // 标签 请求
      this.qsForm.tags = null
      const res2 = await getTagsOptions({ subjectID: this.qsForm.subjectID })
      this.tagName = res2.data
    },

    // 学科 请求
    async getSubjectOptions() {
      const { data } = await getSubjectOptions()
      // console.log(data)
      this.subjectName = data
    },

    // 企业 请求
    async getCompanyOptions() {
      const { data: { items }} = await getCompanyOptions({ pagesize: 999999 })
      // console.log(items)
      this.company = items
    }

  }

}
</script>

<style scoped lang='scss'>
.questions-new ::v-deep .quill-editor{
  height: 200px;
  margin-bottom: 50px;
}
.questions-new::v-deep .quill-editor.ql-snow{
  padding: 0 8px;
}

.option_item{
  padding-bottom: 20px ;

}

.avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  margin-left: 10px;

}

.questions-new ::v-deep .avatar-uploader .el-upload:hover{
  border-color: #8df;

}
.questions-new ::v-deep .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
  }
.questions-new ::v-deep .avatar-uploader i{
  position: absolute;
  right: 0;
  top:0;
  transform: translate(50%,-50%);
  // background-color: #fff;
  font-size: 18px;
  color:rgb(92, 82, 82)
}
.avatar {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100px;
  height: 60px;
  display: block;
  // overflow: hidden;
}
</style>
